<template>
  <div class="shopping-cart-page">
    <div class="container">
      <h1>购物车</h1>
      
      <!-- 购物车为空 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车为空">
          <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
        </el-empty>
      </div>
      
      <!-- 购物车商品列表 -->
      <div v-else>
        <el-table :data="cartItems" border style="width: 100%">
          <el-table-column prop="id" label="商品ID" width="80" />
          <el-table-column label="商品信息" width="300">
            <template #default="scope">
              <div class="product-info">
                <img 
                  :src="getProductImage(scope.row)" 
                  :alt="scope.row.name" 
                  class="product-image"
                  @error="handleImageError"
                />
                <div class="product-details">
                  <div class="product-name">{{ scope.row.name }}</div>
                  <div class="product-price">￥{{ scope.row.price }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              ￥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="scope.row.stock" 
                size="small"
                @change="handleQuantityChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="removeFromCart(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 购物车统计 -->
        <div class="cart-summary">
          <div class="summary-item">
            <span>商品总数：</span>
            <span>{{ totalQuantity }} 件</span>
          </div>
          <div class="summary-item">
            <span>商品金额：</span>
            <span>￥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>运费：</span>
            <span>￥{{ shippingFee.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span>应付总额：</span>
            <span>￥{{ (totalAmount + shippingFee).toFixed(2) }}</span>
          </div>
          
          <div class="cart-actions">
            <el-button @click="$router.push('/')">继续购物</el-button>
            <el-button type="primary" @click="checkout">去结算</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCart, updateCartItemQuantity, removeFromCart } from '@/api/cartApi'

export default {
  name: 'ShoppingCart',
  data() {
    return {
      cartItems: [],
      shippingFee: 0.00 // 运费
    }
  },
  mounted() {
    this.fetchCartData()
  },
  computed: {
    // 计算商品总数
    totalQuantity() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    // 计算商品总金额
    totalAmount() {
      return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
    }
  },
  methods: {
    // 获取商品图片
    getProductImage(product) {
      if (product.image) {
        try {
          // 尝试返回实际图片路径
          return require(`@/assets/files/${product.image}`)
        } catch (error) {
          // 如果图片不存在，返回默认图片
          console.warn(`商品图片加载失败: ${product.image}`, error)
          return require('@/assets/images/default_product.jpg')
        }
      }
      // 如果没有image，返回默认图片
      return require('@/assets/images/default_product.jpg')
    },
    
    // 图片加载错误处理
    handleImageError(event) {
      event.target.src = require('@/assets/images/default_product.jpg')
    },
    
    // 获取购物车数据
    async fetchCartData() {
      try {
        const response = await getCart()
        console.log('购物车数据:', response)
        // 直接检查返回的数据是否为数组
        if (Array.isArray(response)) {
          // 映射后端数据到前端数据结构
          this.cartItems = response.map(item => ({
            id: item.productId,
            name: item.productName,
            price: item.price,
            quantity: item.quantity,
            image: item.image || '@/assets/images/default_product.jpg'
          }))
        } else {
          this.cartItems = []
        }
      } catch (error) {
        console.error('获取购物车数据失败:', error)
        this.$message.error('获取购物车数据失败: ' + (error.message || '网络错误'))
        this.cartItems = []
      }
    },
    
    // 处理商品数量变化
    async handleQuantityChange(item) {
      try {
        const response = await updateCartItemQuantity(item.id, item.quantity)
        // 修改这里以适配返回简单字符串"success"的API
        if (response === 'success') {
          this.$message.success('商品数量已更新')
          // 重新获取购物车数据以确保同步
          await this.fetchCartData()
          // 触发全局事件通知其他组件购物车已更新
          window.dispatchEvent(new Event('cart-updated'))
        } else {
          this.$message.error(response || '更新商品数量失败')
        }
      } catch (error) {
        console.error('更新商品数量失败:', error)
        this.$message.error('更新商品数量失败: ' + (error.message || '网络错误'))
      }
    },
    
    // 从购物车删除商品
    async removeFromCart(item) {
      this.$confirm(`确定要从购物车中删除 ${item.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await removeFromCart(item.id)
          // 修改这里以适配返回简单字符串"success"的API
          if (response === 'success') {
            // 从本地数组中移除商品
            const index = this.cartItems.findIndex(cartItem => cartItem.id === item.id)
            if (index !== -1) {
              this.cartItems.splice(index, 1)
              this.$message.success('商品已从购物车中删除')
              // 触发全局事件通知其他组件购物车已更新
              window.dispatchEvent(new Event('cart-updated'))
            }
          } else {
            this.$message.error(response || '删除商品失败')
          }
        } catch (error) {
          console.error('删除商品失败:', error)
          this.$message.error('删除商品失败: ' + (error.message || '网络错误'))
        }
      }).catch(() => {
        // 用户取消删除
      })
    },
    
    // 去结算
    checkout() {
      // 检查用户是否已登录
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      // 检查购物车是否为空
      if (this.cartItems.length === 0) {
        this.$message.warning('购物车为空')
        return
      }
      
      // 跳转到订单确认页面，传递购物车数据
      this.$router.push({
        name: 'OrderConfirmation',
        params: { 
          cartItems: JSON.stringify(this.cartItems),
          totalAmount: (this.totalAmount + this.shippingFee).toFixed(2)
        }
      })
    }
  }
}
</script>

<style scoped>
.shopping-cart-page {
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
}

/* 商品信息样式 */
.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-price {
  color: #ff4e00;
  font-weight: bold;
}

/* 购物车统计样式 */
.cart-summary {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 16px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
  color: #ff4e00;
  border-top: 1px solid #ddd;
  padding-top: 10px;
  margin-top: 10px;
}

.cart-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-summary {
    padding: 15px;
  }
  
  .summary-item {
    font-size: 14px;
  }
  
  .cart-actions {
    flex-direction: column;
  }
  
  .cart-actions .el-button {
    width: 100%;
    margin-bottom: 10px;
  }
}

/* 解决el-table样式被全局样式覆盖的问题 */
:deep(.el-table) {
  margin: 0 !important;
  width: 100% !important;
}

:deep(.el-table__header-wrapper) {
  margin: 0 !important;
}

:deep(.el-table__header) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

:deep(.el-table__body-wrapper) {
  margin: 0 !important;
}

:deep(.el-table__body) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

:deep(table) {
  margin: 0 !important;
  border-collapse: separate !important;
  table-layout: fixed !important;
}
</style>